package com.qiantu.phone.ui.activity;

import android.content.Intent;
import android.view.View;

import com.hjq.http.listener.HttpCallback;
import com.hjq.toast.ToastUtils;
import com.qiantu.api.db.LLDeviceDBManager;
import com.qiantu.api.entity.QueryCodeResultBean;
import com.qiantu.api.http.LLHttpManager;
import com.qiantu.api.http.model.HttpData;
import com.qiantu.phone.R;
import com.qiantu.phone.app.AppActivity;
import com.qiantu.phone.widget.StatusSeekBar;

import java.util.HashMap;
import java.util.Map;

import okhttp3.Call;

/**
 * time   : 2021/12/22
 */
public final class SensitivitySettingActivity extends AppActivity {

    private StatusSeekBar statusSeekBar;
    private int mValue = 10;
    private String queryCode;
    private int totalTime = 20 * 1000;
    private long startTime;
    private String deviceSerialNo;

    @Override
    protected int getLayoutId() {
        return R.layout.activity_sensitivity_setting;
    }

    @Override
    protected void initView() {
        statusSeekBar = findViewById(R.id.status_seek_bar);
        statusSeekBar.setOnSeekBarChangeListener(new StatusSeekBar.OnSeekBarChangeListener() {
            @Override
            public void onValueChanged(int value) {
                mValue = value;
            }

            @Override
            public void onStartTrackingTouch() {

            }

            @Override
            public void onStopTrackingTouch(int value) {
                mValue = value;
            }
        });
    }

    @Override
    protected void initData() {
        mValue = getInt("value");
        deviceSerialNo = getString("deviceSerialNo");
        String productmodel = getString("productModel");
        if(productmodel.equals("0x2502")){
            statusSeekBar.setMinMaxValue(10,254);
        }
        statusSeekBar.setValue(mValue);
    }

    @Override
    public void onRightClick(View view) {
        setSensitivity();
    }

    private Runnable countRunnable = new Runnable() {
        @Override
        public void run() {
            if(System.currentTimeMillis() - startTime > totalTime){
                handleFailed();
            }else{
                postDelayed(this, 990);
            }
        }
    };

    private void setSensitivity() {
        startTime = System.currentTimeMillis();
        post(countRunnable);
        Map<String, Object> stateData = new HashMap<>();
        Map<String, Object> settings = new HashMap<>();
        settings.put("sensitivity", mValue);
        stateData.put("settings", settings);
        LLHttpManager.sendDeviceSetting(this, deviceSerialNo, stateData, new HttpCallback<HttpData<QueryCodeResultBean<String, Object>>>(null) {
            @Override
            public void onStart(Call call) {
                if(getContext() != null && getContext() instanceof AppActivity){
                    ((AppActivity)getContext()).showDialog(getResources().getString(R.string.setting));
                }
            }

            @Override
            public void onSucceed(HttpData<QueryCodeResultBean<String, Object>> result) {
                handleResult(result.getData());
            }

            @Override
            public void onFail(Exception e) {
                handleFailed();
            }

            @Override
            public void onEnd(Call call) {

            }
        });
    }

    private void querySendDeviceSetting(){
        LLHttpManager.querySendDeviceSetting(this, queryCode, new HttpCallback<HttpData<QueryCodeResultBean<String, Object>>>(null){
            @Override
            public void onStart(Call call) {
            }

            @Override
            public void onSucceed(HttpData<QueryCodeResultBean<String, Object>> result) {
                handleResult(result.getData());
            }

            @Override
            public void onFail(Exception e) {
                super.onFail(e);
                handleFailed();
            }

            @Override
            public void onEnd(Call call) {
            }
        });
    }

    private void handleResult(QueryCodeResultBean data){
        queryCode = data.getQueryCode();
        //发起操作:0 正在操作:1 操作成功:2 操作失败:3 操作异常:4 停止操作:5
        if(data != null){
            switch (data.getQueryStateType()){
                case 0:
                case 1:
                    getHandler().postDelayed(pollingRunnable, 1000);
                    break;
                case 2:
                    getHandler().removeCallbacksAndMessages(null);
                    LLDeviceDBManager.getInstance(getContext()).updateDeviceSensitivity(deviceSerialNo, mValue);
                    Intent intent = new Intent();
                    intent.putExtra("sensitivity", mValue);
                    setResult(RESULT_OK, intent);
                    hideDialog();
                    ToastUtils.show(R.string.set_success);
                    finish();
                    break;
                case 3:
                case 4:
                case 5:
                    handleFailed();
                    break;
            }
        }
    }

    private void handleFailed(){
        getHandler().removeCallbacksAndMessages(null);
        ToastUtils.show(R.string.set_failed);
        hideDialog();
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        getHandler().removeCallbacksAndMessages(null);
    }

    private Runnable pollingRunnable = new Runnable(){
        @Override
        public void run() {
            querySendDeviceSetting();
        }
    };
}